package com.wifeacountbook.util;


import java.util.HashMap;

import android.database.SQLException;
import com.wifeacountbook.R;
import com.wifeacountbook.util.AcountKeeper.ConsumeDetail;
import com.wifeacountbook.util.AcountKeeper.ConsumeType;
import com.wifeacountbook.util.AcountKeeper.IncomeDetail;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class AcountKeepProvider extends ContentProvider {
	private static final int CONSUME_DETAIL_ID_MATCHER_NUM = 2;
	private static final int CONSUME_DETAIL_MATCHER_NUM = 1;
	private static final int INCOME_DETAIL_MATCHER_NUM = 11;
	private static final int INCOME_DETAIL_ID_MATCHER_NUM = 12;
	private static final int CONSUME_TYPE_MATCHER_NUM = 3;
	private static final int CONSUME_TYPE_ID_MATCHER_NUM = 4;
	private static final String ACOUNT_TABLE_NAME_CONSUME_DETAIL = "acount_consume_info";
	private static final String ACOUNT_TABLE_NAME_CONSUME_TYPE = "acount_consume_type";
	private static final String ACOUNT_TABLE_NAME_INCOME_DETAIL = "acount_income_info";
	
	private static HashMap<String,String> DETAIL_PROJECT_MAP = new HashMap<String,String>();
	private static HashMap<String,String> Type_PROJECT_MAP = new HashMap<String,String>();
	private static HashMap<String,String> INCOME_DETAIL_PROJECT_MAP = new HashMap<String,String>();

	public SQLiteOpenHelper getSQLiteOpenHelper(Context ctx){
		return new AcountDBOpenHelper(ctx);
	}
	
	private AcountDBOpenHelper dbHelper;
	private final static UriMatcher uriMatcher;

	@Override
	public boolean onCreate() {
		dbHelper = new AcountDBOpenHelper(getContext());
		return false;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		int count = 0;
		switch(uriMatcher.match(uri)){
		case CONSUME_DETAIL_MATCHER_NUM:
			count = db.delete(ACOUNT_TABLE_NAME_CONSUME_DETAIL, selection, selectionArgs);
			break;
		case CONSUME_DETAIL_ID_MATCHER_NUM:
			String tWhereClause = ConsumeDetail._ID +"=" + uri.getPathSegments().get(1)+(selection == null?" AND "+selection:"");
			count = db.delete(ACOUNT_TABLE_NAME_CONSUME_DETAIL, tWhereClause, selectionArgs);
			break;
		case CONSUME_TYPE_MATCHER_NUM:
			count = db.delete(ACOUNT_TABLE_NAME_CONSUME_TYPE, selection, selectionArgs);
			break;
		case CONSUME_TYPE_ID_MATCHER_NUM:
			String whereClause = ConsumeType._ID + "=" + uri.getPathSegments().get(1)+(selection== null?" AND "+selection:"");
			count = db.delete(ACOUNT_TABLE_NAME_CONSUME_TYPE, whereClause, selectionArgs);
			break;
		default:
				throw new IllegalArgumentException("illegal uri "+ uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch(uriMatcher.match(uri)){
		case CONSUME_DETAIL_MATCHER_NUM:
			return ConsumeDetail.CONTENT_TYPE;
		case CONSUME_DETAIL_ID_MATCHER_NUM:
			return ConsumeDetail.CONTENT_ITEM_TYPE;
		case CONSUME_TYPE_MATCHER_NUM:
			return ConsumeType.CONTENT_TYPE;
		case CONSUME_TYPE_ID_MATCHER_NUM:
			return ConsumeType.CONTENT_ITEM_TYPE;
		default:
				throw new IllegalArgumentException("unknow uri:"+uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		long id = 0;
		switch(uriMatcher.match(uri)){
		case CONSUME_DETAIL_MATCHER_NUM:
		{	
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			ContentValues cValues = checkDetailDefaultValues(values);
			id = db.insert(ACOUNT_TABLE_NAME_CONSUME_DETAIL, ConsumeDetail.MONEY,	cValues);
			if(id > 0){
				Uri insertedUri = ContentUris.withAppendedId(ConsumeDetail.CONTENT_URI, id);
				getContext().getContentResolver().notifyChange(insertedUri, null);
				return insertedUri;
			}
			break;
		}
		case CONSUME_TYPE_MATCHER_NUM:
		{
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			ContentValues tValues = checkTypeDefaultValues(values);
			id = db.insert(ACOUNT_TABLE_NAME_CONSUME_TYPE, ConsumeType.TYPENAME, tValues);
			if(id > 0){
				Uri insertedUri = ContentUris.withAppendedId(ConsumeType.CONTENT_URI, id);
				getContext().getContentResolver().notifyChange(insertedUri, null);
				return insertedUri;
			}
			break;
		}
		case INCOME_DETAIL_MATCHER_NUM:
		{
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			ContentValues cValues = checkIncomeDetailDefaultValues(values);
			id = db.insert(ACOUNT_TABLE_NAME_INCOME_DETAIL, IncomeDetail.MONEY, cValues);
			if(id > 0){
				Uri insertedUri = ContentUris.withAppendedId(IncomeDetail.CONTENT_URI, id);
				getContext().getContentResolver().notifyChange(insertedUri, null);
				return insertedUri;
			}
			break;
		}
		default:
				throw new IllegalArgumentException("unknow uri:" + uri);
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	private ContentValues checkIncomeDetailDefaultValues(ContentValues values) {
		long now = System.currentTimeMillis();
		ContentValues cValues = null;
		if (values == null) {
			cValues = new ContentValues();
		} else {
			cValues = new ContentValues(values);
		}
		if (!cValues.containsKey(IncomeDetail.ACOUNTID)) {
			cValues.put(IncomeDetail.ACOUNTID, "");
		}

		if(!cValues.containsKey(IncomeDetail.INCOMEITEM)){
			cValues.put(IncomeDetail.INCOMEITEM, "");
		}
		if (!cValues.containsKey(IncomeDetail.ADDRESS)) {
			cValues.put(IncomeDetail.ADDRESS, "");
		}

		if (!cValues.containsKey(IncomeDetail.INCOMETIME)) {
			cValues.put(IncomeDetail.INCOMETIME, now);
		}

		if (!cValues.containsKey(IncomeDetail.INCOMETYPEID)) {
			cValues.put(IncomeDetail.INCOMETYPEID, "");
		}

		if (!cValues.containsKey(IncomeDetail.DESC)) {
			cValues.put(IncomeDetail.DESC, "");
		}

		if (!cValues.containsKey(IncomeDetail.PAYTYPE)) {
			cValues.put(IncomeDetail.PAYTYPE, getContext().getResources().getString(R.string.str_paytype));
		}
		return cValues;
	}

	private ContentValues checkTypeDefaultValues(ContentValues values) {
		ContentValues tValues = null;
		if(values == null){
			tValues = new ContentValues();
		}else{
			tValues = new ContentValues(values);
		}
		if(tValues.containsKey(ConsumeType.CONTENT_TYPE)){
			tValues.put(ConsumeType.TYPENAME, "");
		}
		if(tValues.containsKey(ConsumeType.CONSUME_TYPE_COLUMN1)){
			tValues.put(ConsumeType.CONSUME_TYPE_COLUMN1, "");
		}
		return tValues;
	}

	private ContentValues checkDetailDefaultValues(ContentValues values) {
		long now = System.currentTimeMillis();
		ContentValues cValues = null;
		if (values == null) {
			cValues = new ContentValues();
		} else {
			cValues = new ContentValues(values);
		}
		if (!cValues.containsKey(ConsumeDetail.ACOUNTID)) {
			cValues.put(ConsumeDetail.ACOUNTID, "");
		}

		if(!cValues.containsKey(ConsumeDetail.CONSUMEITEM)){
			cValues.put(ConsumeDetail.CONSUMEITEM, "");
		}
		if (!cValues.containsKey(ConsumeDetail.ADDRESS)) {
			cValues.put(ConsumeDetail.ADDRESS, "");
		}

		if (!cValues.containsKey(ConsumeDetail.CONSUMETIME)) {
			cValues.put(ConsumeDetail.CONSUMETIME, now);
		}

		if (!cValues.containsKey(ConsumeDetail.CONSUMETYPEID)) {
			cValues.put(ConsumeDetail.CONSUMETYPEID, "");
		}

		if (!cValues.containsKey(ConsumeDetail.DESC)) {
			cValues.put(ConsumeDetail.DESC, "");
		}

		if (!cValues.containsKey(ConsumeDetail.PAYTYPE)) {
			cValues.put(ConsumeDetail.PAYTYPE, getContext().getResources().getString(R.string.str_paytype));
		}
		return cValues;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		String orderBy = sortOrder;
		SQLiteQueryBuilder sq = new SQLiteQueryBuilder();
		switch(uriMatcher.match(uri)){
		case CONSUME_DETAIL_ID_MATCHER_NUM:
			sq.setTables(ACOUNT_TABLE_NAME_CONSUME_DETAIL);
			sq.setProjectionMap(DETAIL_PROJECT_MAP);
			sq.appendWhere(ConsumeDetail._ID + "="+uri.getPathSegments().get(1));
			if(TextUtils.isEmpty(sortOrder)){
				orderBy = ConsumeDetail.DEFAULT_SORT_ORDER;
			}
			break;
		case CONSUME_DETAIL_MATCHER_NUM:
			sq.setTables(ACOUNT_TABLE_NAME_CONSUME_DETAIL);
			sq.setProjectionMap(DETAIL_PROJECT_MAP);
			if(TextUtils.isEmpty(sortOrder)){
				orderBy = ConsumeDetail.DEFAULT_SORT_ORDER;
			}
			break;
		//query for income info with id
		case INCOME_DETAIL_ID_MATCHER_NUM:
			sq.setTables(ACOUNT_TABLE_NAME_INCOME_DETAIL);
			sq.setProjectionMap(INCOME_DETAIL_PROJECT_MAP);
			sq.appendWhere(IncomeDetail._ID + "=" +uri.getPathSegments().get(1));
			if(TextUtils.isEmpty(sortOrder)){
				orderBy = IncomeDetail.DEFAULT_SORT_ORDER;
			}
			break;
		//query for all income info 
		case INCOME_DETAIL_MATCHER_NUM:
			sq.setTables(ACOUNT_TABLE_NAME_INCOME_DETAIL);
			sq.setProjectionMap(INCOME_DETAIL_PROJECT_MAP);
			if(TextUtils.isEmpty(sortOrder)){
				orderBy = IncomeDetail.DEFAULT_SORT_ORDER;
			}
			break;
			
		case CONSUME_TYPE_ID_MATCHER_NUM:
			sq.setTables(ACOUNT_TABLE_NAME_CONSUME_TYPE);
			sq.setProjectionMap(Type_PROJECT_MAP);
			sq.appendWhere(ConsumeType._ID + "=" + uri.getPathSegments().get(1));
			if(TextUtils.isEmpty(sortOrder)){
				orderBy = ConsumeType.DEFAULT_SORT_ORDER;
			}
			break;
		case CONSUME_TYPE_MATCHER_NUM:
			sq.setTables(ACOUNT_TABLE_NAME_CONSUME_TYPE);
			sq.setProjectionMap(Type_PROJECT_MAP);
			if(TextUtils.isEmpty(sortOrder)){
				orderBy = ConsumeType.DEFAULT_SORT_ORDER;
			}else{
				sortOrder = sortOrder + "DESC ";
			}
			break;
		default:
			throw new IllegalArgumentException("illegal uri "+uri);
		}
		
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = sq.query(db, projection, selection, selectionArgs, null, null, orderBy);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues cValues = null;
		int count = 0;
		switch (uriMatcher.match(uri)) {
		case CONSUME_DETAIL_MATCHER_NUM:
			cValues = checkDetailDefaultValues(values);
			if(values == null){
				cValues = new ContentValues();
			}else{
				cValues = new ContentValues(values);
			}
			count = db.update(ACOUNT_TABLE_NAME_CONSUME_DETAIL, cValues,selection, selectionArgs);
			break;
		case CONSUME_DETAIL_ID_MATCHER_NUM:
			cValues = checkDetailDefaultValues(values);
			String tWhereClause = ConsumeDetail._ID +"=" + uri.getPathSegments().get(1)+(selection == null?" AND "+selection:"");
			count = db.update(ACOUNT_TABLE_NAME_CONSUME_DETAIL, values,tWhereClause, selectionArgs);
			break;
		case CONSUME_TYPE_MATCHER_NUM:
			cValues = checkTypeDefaultValues(values);
			count = db.update(ACOUNT_TABLE_NAME_CONSUME_TYPE, values, selection, selectionArgs);
			break;
		case CONSUME_TYPE_ID_MATCHER_NUM:
			cValues = checkTypeDefaultValues(values);
			String whereClause = ConsumeType._ID +"=" + uri.getPathSegments().get(1)+(selection == null?" AND "+selection:"");
			count = db.update(ACOUNT_TABLE_NAME_CONSUME_TYPE, values, whereClause, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("unknow uri:" + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(AcountKeeper.AUTHORITY, ConsumeDetail.CONTENT_PATH,CONSUME_DETAIL_MATCHER_NUM);
		uriMatcher.addURI(AcountKeeper.AUTHORITY, IncomeDetail.CONTENT_PATH, INCOME_DETAIL_MATCHER_NUM);
		uriMatcher.addURI(AcountKeeper.AUTHORITY, IncomeDetail.CONTENT_PATH
				+"/#", INCOME_DETAIL_ID_MATCHER_NUM);
		uriMatcher.addURI(AcountKeeper.AUTHORITY, ConsumeDetail.CONTENT_PATH
				+ "/#", CONSUME_DETAIL_ID_MATCHER_NUM);
		uriMatcher.addURI(AcountKeeper.AUTHORITY, ConsumeType.CONTENT_PATH, CONSUME_TYPE_MATCHER_NUM);
		uriMatcher.addURI(AcountKeeper.AUTHORITY, ConsumeType.CONTENT_PATH+"/#", CONSUME_TYPE_ID_MATCHER_NUM);

		DETAIL_PROJECT_MAP.put(ConsumeDetail._ID, ConsumeDetail._ID);
		DETAIL_PROJECT_MAP.put(ConsumeDetail.ACOUNTID, ConsumeDetail.ACOUNTID);
		DETAIL_PROJECT_MAP.put(ConsumeDetail.ADDRESS, ConsumeDetail.ADDRESS);
		DETAIL_PROJECT_MAP.put(ConsumeDetail.CONSUMETIME, ConsumeDetail.CONSUMETIME);
		DETAIL_PROJECT_MAP.put(ConsumeDetail.CONSUMETYPEID, ConsumeDetail.CONSUMETYPEID);
		DETAIL_PROJECT_MAP.put(ConsumeDetail.DESC, ConsumeDetail.DESC);
		DETAIL_PROJECT_MAP.put(ConsumeDetail.MONEY, ConsumeDetail.MONEY);
		DETAIL_PROJECT_MAP.put(ConsumeDetail.PAYTYPE, ConsumeDetail.PAYTYPE);
		DETAIL_PROJECT_MAP.put(ConsumeDetail.CONSUMEITEM, ConsumeDetail.CONSUMEITEM);
		
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail._ID, IncomeDetail._ID);
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail.ACOUNTID, IncomeDetail.ACOUNTID);
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail.ADDRESS, IncomeDetail.ADDRESS);
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail.INCOMETIME, IncomeDetail.INCOMETIME);
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail.INCOMETYPEID, IncomeDetail.INCOMETYPEID);
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail.DESC, IncomeDetail.DESC);
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail.MONEY, IncomeDetail.MONEY);
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail.PAYTYPE, IncomeDetail.PAYTYPE);
		INCOME_DETAIL_PROJECT_MAP.put(IncomeDetail.INCOMEITEM, IncomeDetail.INCOMEITEM);
		
		
		Type_PROJECT_MAP.put(ConsumeType._ID, ConsumeType._ID);
		Type_PROJECT_MAP.put(ConsumeType.TYPENAME, ConsumeType.TYPENAME);
		Type_PROJECT_MAP.put(ConsumeType.TYPE, ConsumeType.TYPE);
		Type_PROJECT_MAP.put(ConsumeType.CONSUME_TYPE_COLUMN1, ConsumeType.CONSUME_TYPE_COLUMN1);
		
		
	}
}
